<template>
  <div>
    <el-dialog
      :visible.sync="addFiledialogVisible"
      :append-to-body="true"
      title="新增文档"
    >
      <el-form ref="addForm" :model="addFormData" size="mini" label-width="100px">
        <el-form-item label="文档名称 :" prop="fileName">
          <el-input v-model="addFormData.fileName" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="上传文档 :" prop="file">
          <el-upload
            ref="uploadRef"
            action=""
            :on-change="fileChange"
            :auto-upload="false"
            :file-list="fileList"
            :limit="1"
            :http-request="uploadFile"
            :on-exceed="handleExceed"
            :on-remove="removeFile"
          >
            <el-button type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注 :" prop="description">
          <el-input v-model="addFormData.description" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" size="mini" @click="submit">确定</el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postAction } from '@/api/manage'
import { Message } from 'element-ui'

export default {
  name: '',
  props: {
    addFileDto: {
      type: Object,
      defalut: {}
    }
  },
  data() {
    return {
      addFiledialogVisible: false,
      fileList: [],
      addFormData: {
        fileName: '',
        description: '',
        file: null
      }
    }
  },
  computed: {},

  mounted() {

  },
  created() {
  },
  methods: {
    show() {
      this.addFiledialogVisible = true
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        '每次只允许上传一个文档，请先点击文件右侧删除图标后再重新选择'
      )
    },
    /**
     * 获取检验规则
     * key 表单prop
     */
    // getRules(key) {
    //   const rulesMap = {
    //     fileName: [
    //       { required: true, message: '名称不能为空' },
    //       { min: 1, max: 64, message: '长度在64个字符以内' },
    //       { validator: validateIllegality, trigger: 'blur' }
    //     ],
    //     description: [
    //       { min: 1, max: 256, message: '长度在256个字符以内', trigger: 'blur' }
    //     ],
    //     tagIds: [
    //       { required: true, message: '类型不能为空', trigger: 'change' }
    //     ],
    //     file: [{ required: true, message: '文件不能为空', trigger: 'change' }]
    //   }
    //   return rulesMap[key]
    // },
    /**
     * 表单初始化
     */
    dialogInit() {
      this.fileList = []
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },
    /**
     * 关闭弹窗
     */
    cancel() {
      this.dialogInit()
      // this.$emit('handleChild', { type: 'close' })
      this.addFiledialogVisible = false
    },
    /**
     * 上传文件
     */
    uploadFile(param) {
      const fileSize = Math.round((param.file.size * 100) / (1024 * 1024)) / 100
      if (fileSize > 20) {
        this.$message({
          type: 'warning',
          message: '文件大小不可超过20MB !'
        })
        return
      }
      this.addFormData.file = new FormData()
      this.addFormData.file.append('file', param.file)
      this.addFormData.file.append('fileName', this.addFormData.fileName)
      if (this.addFileDto !== undefined) {
        this.addFormData.file.append('orderId', this.addFileDto.orderId === undefined ? '' : this.addFileDto.orderId)
        this.addFormData.file.append('projectId', this.addFileDto.projectId === undefined ? '' : this.addFileDto.projectId)
        this.addFormData.file.append('supplierId', this.addFileDto.supplierId === undefined ? '' : this.addFileDto.supplierId)
        this.addFormData.file.append('contractId', this.addFileDto.contractId === undefined ? '' : this.addFileDto.contractId)
      }
      this.addFormData.file.append('fileComment', this.addFormData.description)
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      postAction('/purchase/file/save', this.addFormData.file)
        .then(({ msg }) => {
          this.cancel()
          // this.$emit('handleChild', { type: 'getList' })
          this.$emit('handleChild', { type: 'addFileComplete' })
          Message.success(msg)
          loading.close()
        })
    },
    /**
     * 移除文件
     */
    removeFile(file, fileList) {
      this.addFormData.file = null
      if (!fileList.length) {
        this.addFormData.fileName = ''
      }
    },
    /**
     * 去掉文件后缀
     */
    splitFileName(fileText) {
      var pattern = /\.{1}[a-z]{1,}$/
      if (pattern.exec(fileText) !== null) {
        return fileText.slice(0, pattern.exec(fileText).index)
      } else {
        return fileText
      }
    },
    /**
     * 选取文件的回调
     */
    fileChange(file, fileList) {
      this.addFormData.fileName = this.splitFileName(file.name)
      this.addFormData.file = new FormData()
      this.addFormData.file.append('file', file)
      this.$refs.addForm && this.$refs.addForm.validateField('file')
    },

    /**
     * 提交
     */
    submit() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$refs.uploadRef && this.$refs.uploadRef.submit()
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.el-form {
  padding: 1rem 1rem 0 1rem;
  .el-cascader {
    width: 100%;
  }
}
</style>
